package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"novel/cache"
	"novel/models"
)

type ReadsController struct {
	beego.Controller
}

func (c *ReadsController) PageList() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	//分页展示
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Reads{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	var novelId []interface{}
	userId, _ := c.GetInt("user_id")
	models.DB.Model(&models.Reads{}).Select("novel_id").Where("user_id = ?", userId).Find(&novelId)
	var reads []models.Novel
	models.DB.Offset(offset).Limit(size).Where("id in (?)", novelId).Find(&reads)
	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"msg":     "展示成功",
		"data":    reads,
		"page":    page,
		"size":    size,
		"count":   count,
		"sumpage": sumpage,
	}
	c.ServeJSON()
}

func (c *ReadsController) List() {
	cacheData := cache.Rdb.Get(cache.Ctx, "reads_list").Val()
	var reads []models.Novel
	if cacheData == "" {
		var novelId []interface{}
		userId, _ := c.GetInt("user_id")
		models.DB.Model(&models.Reads{}).Select("novel_id").Where("user_id = ?", userId).Find(&novelId)
		models.DB.Where("id in (?)", novelId).Find(&reads)
		jsonData, _ := json.Marshal(reads)
		cache.Rdb.Set(cache.Ctx, "reads_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &reads)
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "展示成功",
			"data": reads,
		}
		c.ServeJSON()
	}

}

func (c *ReadsController) Del() {
	var reads models.Reads
	id, _ := c.GetInt("id")
	models.DB.Where("id = ?", id).First(&reads)
	if reads.Status == "已阅读" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "已阅读的记录禁止删除",
		}
		c.ServeJSON()
		return
	}
	reads.Del()
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
}
